package service.impl;

import java.util.List;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import pojo.Address;
import pojo.Customer;
import service.CustomerManager;
import dao.CustomerDao;

@Service(value="customerManager")
public class CustomerManagerImpl implements CustomerManager {
	@Resource(name="customerDao")
	private CustomerDao customerDao;
	
	@Override
	@Transactional
	public Customer addCustomer(Customer c) {
		return customerDao.addCustomer(c);
	}

	@Override
	@Transactional
	public Customer checkCustomer(String name, String password) {
		return customerDao.checkCustomer(name, password);
	}

	@Override
	public Customer loadCustomer(String customerId) {
		return customerDao.loadCustomer(customerId);
	}

	@Override
	@Transactional
	public Customer setCustomerDefaultAddress(Customer c, String addressName) {
		Customer customer = customerDao.loadCustomer(c.getId());
		List<Address> addressList = customer.getAddressList();
		for (Address address : addressList){
			address.setIsDefaultAddress(false);
		}
		for (Address address : addressList){
			System.out.println("into address ..");
			if(address.getName().equals(addressName)){
				System.out.println("update address ..");
				address.setIsDefaultAddress(true);
				break;
			}
		}

		return customerDao.updateCustomer(customer);
	}

	@Override
    @Transactional
	public Customer updateCustomerAddress(Customer c, String oldValue, String newValue) {
        Customer customer = customerDao.loadCustomer(c.getId());
        List<Address> list = customer.getAddressList();
        for (Address address : list){
            System.out.println(address);
            if(oldValue.equals(address.getName())){
                address.setName(newValue);
            }
        }
        System.out.println(customer);
        return customerDao.updateCustomer(customer);
	}

	@Override
	@Transactional
	public Customer deleteCustomerAddress(Customer c, Address a) {
		Customer customer = customerDao.loadCustomer(c.getId());
		List<Address> list = customer.getAddressList();
		list.remove(a);
		return customerDao.updateCustomer(customer);
	}

	@Override
	@Transactional
	public Customer addCustomerAddress(Customer c, Address a) {
		Customer customer = customerDao.loadCustomer(c.getId());
		List<Address> addressList = customer.getAddressList();
		for (Address address : addressList){
			address.setIsDefaultAddress(false);
		}

		a.setIsDefaultAddress(true);
		customer.getAddressList().add(a);
		return customerDao.updateCustomer(customer);
	}

}
